package com.lagou.edu.factory;

import com.lagou.edu.anno.Autowired;
import com.lagou.edu.anno.Repository;
import com.lagou.edu.anno.Service;
import com.lagou.edu.anno.Transactional;
import com.lagou.edu.service.impl.TransferServiceImpl;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.reflections.Reflections;
import org.reflections.scanners.FieldAnnotationsScanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ConfigurationBuilder;

import java.io.File;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author 应癫
 *
 * 工厂类，生产对象（使用反射技术）
 */
public class BeanFactory {

    /**
     * 任务一：读取解析xml，通过反射技术实例化对象并且存储待用（map集合）
     * 任务二：对外提供获取实例对象的接口（根据id获取）
     */

    private static Map<String,Object> map = new HashMap<>();  // 存储对象

    //存储bean类型和beanId的对应关系
    private static Map<String,String> beanTypeIdMap = new HashMap<>();

    private static void addIntoMap(Class<?> aClass,String beanId,Object bean){
        for (Class<?> anInterface : aClass.getInterfaces()) {
            beanTypeIdMap.put(anInterface.getName(),beanId);
        }
        beanTypeIdMap.put(aClass.getName(),beanId);
        if(aClass.getSuperclass()!=Object.class){
            beanTypeIdMap.put(aClass.getSuperclass().getName(),beanId);
        }
        map.put(beanId,bean);
    }

    static {
        // 任务一：读取解析xml，通过反射技术实例化对象并且存储待用（map集合）
        // 加载xml
        InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
        // 解析xml
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> beanList = rootElement.selectNodes("//bean");
            for (int i = 0; i < beanList.size(); i++) {
                Element element =  beanList.get(i);
                // 处理每个bean元素，获取到该元素的id 和 class 属性
                String id = element.attributeValue("id");        // accountDao
                String clazz = element.attributeValue("class");  // com.lagou.edu.dao.impl.JdbcAccountDaoImpl
                // 通过反射技术实例化对象
                Class<?> aClass = Class.forName(clazz);
                Object o = aClass.newInstance();  // 实例化之后的对象

                // 存储到map中待用
                //map.put(id,o);
                addIntoMap(aClass,id,o);

            }

            // 实例化完成之后维护对象的依赖关系，检查哪些对象需要传值进入，根据它的配置，我们传入相应的值
            // 有property子元素的bean就有传值需求
            List<Element> propertyList = rootElement.selectNodes("//property");
            // 解析property，获取父元素
            for (int i = 0; i < propertyList.size(); i++) {
                Element element =  propertyList.get(i);   //<property name="AccountDao" ref="accountDao"></property>
                String name = element.attributeValue("name");
                String ref = element.attributeValue("ref");

                // 找到当前需要被处理依赖关系的bean
                Element parent = element.getParent();

                // 调用父元素对象的反射功能
                String parentId = parent.attributeValue("id");
                Object parentObject = map.get(parentId);
                // 遍历父对象中的所有方法，找到"set" + name
                Method[] methods = parentObject.getClass().getMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method method = methods[j];
                    if(method.getName().equalsIgnoreCase("set" + name)) {  // 该方法就是 setAccountDao(AccountDao accountDao)
                        method.invoke(parentObject,map.get(ref));
                    }
                }

                // 把处理之后的parentObject重新放到map中
                map.put(parentId,parentObject);
            }

            //下面处理注解生成bean
            List<Element> annoBeanList = rootElement.selectNodes("//component-scan");
            if(annoBeanList!=null && !annoBeanList.isEmpty()){
                //处理注解bean
                annoBean(annoBeanList.get(0).attributeValue("packages"));
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }



    // 任务二：对外提供获取实例对象的接口（根据id获取）
    public static  Object getBean(String id) {
        return map.get(id);
    }

    public static  Object getBean(Class<?> clazz) {
        String beanId = beanTypeIdMap.get(clazz.getName());
        return map.get(beanId);
    }


    private static void annoBean(String packages) throws IllegalAccessException, InstantiationException {
        Reflections reflections = new Reflections(new ConfigurationBuilder().forPackages(packages)
                .addScanners(new SubTypesScanner()).addScanners(new FieldAnnotationsScanner()));
        List<String> transactionalIds = new ArrayList<>();//这里存储@Transactional修饰的beanId
        //获取@Service注解的类
        Set<Class<?>> serviceTypeClass = reflections.getTypesAnnotatedWith(Service.class, true);
        //获取@Repository注解的类
        Set<Class<?>> repositoryTypeClass = reflections.getTypesAnnotatedWith(Repository.class, true);
        //生成@Service修饰的bean
        if(serviceTypeClass!=null && !serviceTypeClass.isEmpty()){
            for (Class<?> clazz : serviceTypeClass) {
                Service service = clazz.getAnnotation(Service.class);
                String id = service.value();
                if(id==null || "".equals(id)){
                    id = clazz.getSimpleName();
                    String temp = String.valueOf(id.charAt(0));
                    id = id.replaceFirst(temp,temp.toLowerCase());
                }
                Object o = clazz.newInstance();
                addIntoMap(clazz,id,o);
                if(clazz.isAnnotationPresent(Transactional.class)){
                    transactionalIds.add(id);
                }
            }
        }
        //生成@Repository修饰的bean
        if(repositoryTypeClass!=null && !repositoryTypeClass.isEmpty()){
            for (Class<?> clazz : repositoryTypeClass) {
                Repository service = clazz.getAnnotation(Repository.class);
                String id = service.value();
                if(id==null || "".equals(id)){
                    id = clazz.getSimpleName();
                    String temp = String.valueOf(id.charAt(0));
                    id = id.replaceFirst(temp,temp.toLowerCase());
                }
                Object o = clazz.newInstance();
                addIntoMap(clazz,id,o);
            }
        }
        //bean属性注入
        Set<Field> autowiredSet = reflections.getFieldsAnnotatedWith(Autowired.class);
        if(autowiredSet!=null && !autowiredSet.isEmpty()){
            for (Field field : autowiredSet) {
                String name = field.getDeclaringClass().getName();
                String beanId = beanTypeIdMap.get(name);
                Object o = map.get(beanId);
                if(o==null){
                    continue;
                }
                String typeName = field.getType().getName();
                String injectFieldId = beanTypeIdMap.get(typeName);
                Object injectField = map.get(injectFieldId);
                field.setAccessible(true);
                field.set(o,injectField);
                map.put(beanId,o);
            }
        }
        //处理@Transactional修饰的类
        if(!transactionalIds.isEmpty()){
            for (String  transactionalId: transactionalIds) {
                Object o = map.get(transactionalId);
                Transactional transactional = o.getClass().getAnnotation(Transactional.class);
                boolean useCglib = false;
                if(transactional.targetProxy().equals("cglib")){
                    useCglib = true;
                }
                if(!useCglib){
                    Class<?>[] interfaces = o.getClass().getInterfaces();
                    useCglib = interfaces==null || interfaces.length==0;
                }
                ProxyFactory proxyFactory = (ProxyFactory) getBean(ProxyFactory.class);
                Object proxyObj = null;
                if(useCglib){
                    proxyObj = proxyFactory.getCglibProxy(o);
                }else{
                    proxyObj = proxyFactory.getJdkProxy(o);
                }
                map.put(transactionalId,proxyObj);

            }
        }
        //return null;

    }

}
